package com.example.auth.util;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

/**
 * packageName com.example.auth.util
 *
 * @author cui haida
 * @version JDK 8
 * 2025/8/6
 */
public class RedisCacheUtils {

    /**
     * get the redis cache key
     * @param point join point
     * @param prefix cache key prefix
     * @return cache key
     * @throws NoSuchMethodException if method not found, throw exception
     */
    public static String getKey(ProceedingJoinPoint point, String prefix) throws NoSuchMethodException {
        return getKeyOfClassPrefix(point, prefix) +
                "_" +
                getMethod(point).getName() +
                getMethodArgs(point.getArgs());
    }

    /**
     * get the redis cache key of class prefix
     *
     * @param point join point
     * @param prefix cache key prefix
     * @return cache key
     */
    public static String getKeyOfClassPrefix(ProceedingJoinPoint point, String prefix) {
        StringBuilder keyPrefix = new StringBuilder();
        if (!StringUtils.isEmpty(prefix)) {
            keyPrefix.append(prefix);
        }
        keyPrefix.append(getClassName(point));
        return keyPrefix.toString();
    }

    /**
     * get class name
     *
     * @param point join point
     * @return class name
     */
    public static String getClassName(ProceedingJoinPoint point) {
        return point.getTarget().getClass().getName().replaceAll("\\.", "_");
    }

    /**
     * get method
     *
     * @param point join point
     * @return method
     * @throws NoSuchMethodException if method not found, throw exception
     */
    public static Method getMethod(ProceedingJoinPoint point) throws NoSuchMethodException {
        Signature signature = point.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        return point.getTarget().getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());
    }

    /**
     * get method args
     *
     * @param params method args
     * @return method args
     */
    private static String getMethodArgs(Object... params) {
        // 没有参数
        if (params == null) {
            return "";
        }
        // 含有参数
        StringBuilder key = new StringBuilder();
        key.append("(");
        for (Object param : params) {
            String json = JsonUtils.toString(param);
            json = json.replaceAll("\"", "'");
            json = json.replaceAll(":", "_");
            json = json.concat("_");
            key.append(JsonUtils.toString(json));
        }
        key.append(")");
        return key.toString().replace("_)", ")");
    }
}